{% extends "school/layout.html" %}

{% set page_title = translate('学生账号管理') %}

{% block content %}
<style>
    .col-sm-4 p{
        margin-bottom: 10px;
        text-align:justify;
    }
</style>
<style>
    #changePhone{
        display: none;
    }
</style>
<div class="m-content">
<form class="form-horizontal" method="POST" id="{{ form.__class__.__name__ }}">
    {{ form.hidden_tag() }}
    <fieldset class="fieldset">
        <legend>{{translate('学生信息')}}<a href="{{ url_for('school.show_study_sessions', student_id=student.id) }}" class="f-right">{{translate('学生成绩')}}</a></legend>

        {% include "school/student_form_common.html" %}
        <div>
            <button class="btn btn-primary" id="save">{{translate('确认')}}</button>
        </div>
    </fieldset>
    <fieldset class="fieldset">
        <legend>{{translate('账号信息')}}</legend>

        <div class="form-group">
            <label class="control-label col-sm-2">{{ form.username.label(class_="norequired") }}:</label>
            <div class="col-sm-4 input-group">
                <span class="input-group-addon" id='school_code'>{{ current_user.school.code }}.</span>
                {{ form.username(class_="form-control", pattern="^[a-zA-z]\w{3,16}$", readonly=True, required=True) }}
            </div>
            {% if form.username.errors %}
            <div class="error">{{ form.username.errors[0] }}</div>
            {% endif %}
        </div>

        <div>
            <button class="btn btn-primary" id="reset_pwd">{{translate('重置密码')}}</button>
        </div>
    </fieldset>
</form>
</div>
<div class="modal" id="checkModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">{{translate('修改手机号码')}}</h4>
            </div>
            <div class="modal-body">
                <div class="form-horizontal">
                    <div class="form-group">
                        <label class="control-label col-sm-2">{{translate('手机号码')}}</label>
                        <div class="col-sm-6">
                            <input type="tel" value="" id="phone_m" placeholder="{{translate('请输入手机号')}}" class="form-control">
                        </div>
                        <div class="col-sm-3">
                            <button class="btn btn-default" id="sendVerify_m">{{translate('发送验证码')}}</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">{{translate('验证码')}}</label>
                        <div class="col-sm-6">
                            <input type="tel" id="verify_m" value="" class="form-control" placeholder="{{translate('请输入6位验证码')}}">
                        </div>
                    </div>
                    <div class="form-group" style="text-align: center;">
                        <button class="btn btn-default" id="done_m" style="width: 80px;margin-right: 30px;">{{translate('确定')}}</button>
                        <button class="btn btn-default" style="width: 80px" data-dismiss="modal">{{translate('取消')}}</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script type="text/javascript">
    var childList = [],
        adultList = [],
        oldList = [];
    function getClassList(courseType,selectedVal){
        $.ajax({
            type: 'get',
            url: '/school/students/get_course_type',
            cache: false,
            success: function(data){
                var d = JSON.parse(data);
                var finArr = [];
                for(var i=0;i<d.length; i++){
                    if(d[i].course_type == 'course_adults'){
                        adultList.push(d[i]);
                    }else if(d[i].course_type == 'course_xi_yang_hong'){
                        oldList.push(d[i]);
                    }else{
                        childList.push(d[i]);
                    }
                }
                if(courseType == 'course_children'){
                    finArr = childList;
                }else if(courseType == 'course_adults'){
                    finArr = adultList;
                }else if(courseType == 'course_xi_yang_hong'){
                    finArr = oldList;
                }else{
                    finArr = childList;
                }
                renderClassList(finArr,selectedVal);
            }
        });
    }
    function renderClassList(classArray,selectedVal){
        var $select = $('select[name = "classes"]');
        $select.empty().append('<option value="-1">{{translate("暂未分配")}}</option>');
        for(var i = 0; i < classArray.length; i++){
            if(classArray[i].ID==selectedVal){
                $select.append('<option selected value="'+classArray[i].ID+'">'+classArray[i].name+'</option>');
            }else{
                $select.append('<option value="'+classArray[i].ID+'">'+classArray[i].name+'</option>');
            }
        }
    }
    $(function(){
        var countDown = 60;
        var isCounting = false;
        var t;
        var isSent = false;
        var sid = "{{ student.id }}"
        var labels = $('#StudentInfoForm').find('label.control-label');
        var cv = $('select[name="classes"]')[0].value;
        var lesson_type_form = $('fieldset .form-group')[0];
        var course_type = '{{student.course_type}}';
        var selected_val = $('select[name="classes"] option:selected').val();

        if(localStorage.lang == 'lang=en'){
            lesson_type_form.style.display = 'none';
        }else{
            //change form when course type changed
            (function(){
                var labelCount = $('label').length;
                var inputCount = $('input').length;
                if(course_type=='course_children'||course_type=='None'){
                    $('#course_type-0').attr('checked','checked');//course_type-0 : children course
                }else{
                    if(course_type=='course_adults'){
                        $('#course_type-1').attr('checked','checked'); //course_type-1 : adult
                    }else{
                        $('#course_type-2').attr('checked','checked'); //course_type-2 : xiyanghong
                    }
                    for(var i = 0; i < labelCount; i++){
                      if($('input[name="course_type"]:checked')[0].id !== 'course_type-0'){
                        //Hide parent name
                        if($('label')[i].htmlFor == 'parent_name'){
                          $($('label')[i]).parent().addClass('hide-item');
                          $($('label')[i]).siblings('input').val('111111');//A default value for backstage pass
                        }
                        //Hide parent
                        if($('label')[i].htmlFor == 'parent_phone'&&$('label')[i].id == ''){
                          $('label')[i].innerHTML = '{{translate("电话")}}';
                        }
                        if($('label')[i].htmlFor == 'parent_email'&&$('label')[i].id == ''){
                          $('label')[i].innerHTML = 'Email';
                        }
                      }else{
                        if($('label')[i].htmlFor == 'parent_name'){
                          $($('label')[i]).parent().removeClass('hide-item')
                        }
                        //Hide parent
                        if($('label')[i].htmlFor == 'parent_phone'&&$('label')[i].id == ''){
                          $('label')[i].innerHTML = '{{translate("家长电话")}}';
                        }
                        if($('label')[i].htmlFor == 'parent_email'&&$('label')[i].id == ''){
                          $('label')[i].innerHTML = '{{translate("家长Email")}}';
                        }
                      }
                    }
                }
                $('input[name="course_type"]:not(:checked)').attr('disabled','disabled')
            })();
        }
        getClassList(course_type,selected_val);

        $.post('/school/students/stu_info',{'sid':sid},function(data){
            var d = JSON.parse(data);
            if(d.code == 0){
                document.getElementById('parent_phone').value=d.phone;
                var in_user_verify_whitelist = '{{ in_user_verify_whitelist }}';
                if ( in_user_verify_whitelist == 'True') {
                    isChecked = true;
                } else {
                    if(d.is_verified){
                        $('#parent_phone').attr('readonly','true');
                        $('#sendVerify').hide();
                        $('#changePhone').show();
                        $('#ver_con').hide();
                        $('#verify').val('111111');
                        isChecked = true;
                    }
                }
            }
        });

        $('#return').bind('click', function(e){
            e.preventDefault();
            window.location.href = "{{ url_for('school.list_students') }}";
        });

        $('#reset_pwd').bind('click', function(e){
            e.preventDefault();
            var student_id = {{ student.id }}
            var url = '/school/students/' + student_id +'/reset_pwd';
            if(localStorage.lang == 'lang=en'){
                url+='?'+localStorage.lang;
            }
            $.post(url, function(data){
                alert(data['msg']);

            }, 'json');
        });
        //新逻辑
        function setTime(val){
          if(isCounting){
              val.attr('disabled','disabled');
              val.addClass('btn-disable');
              val.html('{{translate("在")}}'+countDown+'{{translate("秒后重新发送")}}');
              countDown--;
              if(countDown<0){
                  isCounting = false;
                  countDown = 60;
              }
          }else{
              val.removeAttr('disabled');
              val.removeClass('btn-disable');
              val.html('{{translate("发送验证码")}}');
              clearTimeout(t);
              return false;
          }
          t = setTimeout(function(){
              setTime(val);
          },1050);
        }

        $('#sendVerify').click(function(e){
            e.preventDefault();
            var phone = $.trim($('#parent_phone').val());
            var $this = $(this);
            var pReg = new RegExp('^[0-9]{11}$');
            if(pReg.test(phone)){
                $.post('/school/students/check_phone',{'phone':phone,'course_type':course_type},function(data){
                    var d = JSON.parse(data);
                    if(d.code == 0){
                        $.post('/vcode/send_vcode',{'phone':phone},function(data){
                            var da = JSON.parse(data);
                            if(da.meta.code == 0){
                                isCounting = true;
                                setTime($this);
                            }else{
                                if(da.meta.code == 1){
                                    kalert('{{translate("验证码不正确，请重新输入")}}');
                                }else if(da.meta.code == 2){
                                    kalert('{{translate("发验证码失败，请稍后再试")}}');
                                }
                            }
                        });
                    }else{
                        kalert('{{translate("输入的手机号已经被占用，请检查后重新输入！")}}')
                    }
                });
            }else{
                if(phone == ''){
                    kalert('{{translate("请输入手机号！")}}')
                }else{
                    kalert('{{translate("输入的手机号不符合规范！")}}')
                }
            }
        });

        $('#changePhone').click(function(e){//打开弹出框
            e.preventDefault();
            $('#checkModal').modal('show');
        });

        $('#sendVerify_m').click(function(e){//发送验证码
            e.preventDefault();
            var $this = $(this);
            var phone = $.trim($('#phone_m').val());
            var pReg = new RegExp('^[0-9]{11}$')
            if(pReg.test(phone)){
                $.post('/school/students/check_phone',{'phone':phone,'course_type':course_type},function(data){
                    var d = JSON.parse(data);
                    if(d.code == 0){
                        $.post('/vcode/send_vcode',{'phone':phone},function(data){
                            var da = JSON.parse(data);
                            if(da.meta.code == 0){
                                isCounting = true;
                                setTime($this);
                                isSent = true;
                            }else{
                                kalert('{{translate("发验证码失败，请稍后再试")}}');
                            }
                        });
                    }else{
                        kalert('{{translate("输入的手机号已经被占用，请检查后重新输入！")}}')
                    }
                });
            }else{
                kalert('{{translate("输入的手机号不符合规范！")}}')
            }
        });

        $('#done_m').click(function(e){ //完成
            e.preventDefault();
            var phone = $.trim($('#phone_m').val());
            var ver = $.trim($('#verify_m').val());
            var vReg = new RegExp('^[0-9]{6}$');
            var username = $('#username').val();
            if(isSent){
                if(vReg.test(ver)){
                    $.post('/school/students/update_phone',{
                        'name': username,
                        'phone': phone,
                        'vcode': ver
                    },function(data){
                        var d = JSON.parse(data);
                        if(d.code == 0){
                            $('#checkModal').modal('hide');
                            $('#parent_phone').val(phone);
                            kalert('{{translate("验证成功")}}');
                        }else{
                            kalert('{{translate("验证码错误或已过期")}}')
                        }
                    });
                }else{
                    kalert('{{translate("请输入正确的6位短信验证码")}}')
                }

            }else{
                kalert('{{translate("请先输入手机获取短信验证码！")}}')
            }
        })
        //验证手机号完成
    });
</script>
{% endblock %}
